<?php

/**
 * Katalog produktov
 */
class Catalogue extends Page {

	/**
     * Metoda na zobrazenie triedy
     *
     */
    public function show() {
        global $db, $r;

		parent::show();

        $this->path[] = array(
			"catalogue",
			i18n::t("cat_catalogue")
			);

		//cesty
        $dir    = $r["root"]    . "/data/catalogue/images";
        $webDir = $r["webRoot"] . "/data/catalogue/images";

		//aktivna polozka menu
        $this->active_menu = $db->getCell("
            SELECT id FROM menu
            WHERE link = 'catalogue' AND lang = '{$r["lang"]}'
        ") + 0;


		//pridat produkt do kosika
		if (!empty($_POST[id])) {

			$this->AddToCart();
			return;

		}

		//odobrat z kosika
		if ($r["arg"][1]=="del") {

			$this->removeFromCart($r["arg"][2]);
    		return;

		}


		//odoslanie objednavky
		if (($r["arg"][1]=="cart")&&($r["arg"][2]=="form")) {

			if (!empty($_POST[sent])) {

				$this->processOrder();
				return;

			} else {
				$this->path[] = array(
                    "catalogue/cart/form",
                    i18n::t("cat_form")
                );

				$this->tpl->assign("path",$this->path);
				$this->tpl->display("cart-form.tpl");
				return;

			}
		}

		//vyprazdenie kosika
		if (($r["arg"][1]=="cart")&&($r["arg"][2]=="empty")) {

			unset($_SESSION[cart]);

			rLocate("catalogue/cart");

			return;
		}

		//zobrazenie kosika
		if ($r["arg"][1]=="cart") {

				$this->showCart(false);
				return;
		}

		//akcie s produktom
        if (($r["arg"][1] == "product") && ($id = $r["arg"][2] + 0)) {

			// predvoleny obrazok
            if (($this->checkAccess("editor")) && ($r["arg"][3] == "default-image")  && ($image_id = $r["arg"][4] + 0)) {
                $db->query("
                    UPDATE c_products SET default_image = $image_id
                    WHERE id = $id
                ");
                rLocate("catalogue/product/$id");
                return;
            }

            // zrusit predvoleny obrazok
            if (($this->checkAccess("editor")) && ($r["arg"][3] == "unset-default-image")) {
                $db->query("
                    UPDATE c_products SET default_image = null
                    WHERE id = $id
                ");
                rLocate("catalogue/product/$id");
                return;
            }

            // zmazat obrazok
            if (($this->checkAccess("editor")) && ($r["arg"][3] == "del-image") && ($image_id = $r["arg"][4] + 0)) {
                self::deleteImage($image_id);
                rLocate("catalogue/product/$id");
                return;
            }

            //upload obrazkov
            if (($this->checkAccess("editor")) && ($_POST["action"] == "add")) {

                $weight = $db->getCell("
                    SELECT MAX(weight) FROM c_product_images
                    WHERE product_id = $id
                ") + 1;

                $query = "";



                foreach ($_FILES["image"]["name"] as $i => $name) {
                    if (!$name) continue;
                    $image_id = $db->getCell("SELECT NEXTVAL('c_product_images_id_seq')") + 0;
                    $ext = eregi_replace('(.*)\.([a-zA-Z0-9]{2,4})$', '\\2', $name);


//error_reporting(E_ALL);
                    $this->uploadPhoto($i, $dir, $image_id, true, "catalogue", true, $x);
                   //die();

                    $text = trim($_POST["text"][$i]);
                    if (!get_magic_quotes_gpc()) $text = addslashes($text);

                    foreach ($r["i18n"]["languages"] as $lang => $language) {
                        $query .= "
                            INSERT INTO c_product_images (id, product_id, weight, lang, text, extension)
                            VALUES (
                                $image_id, $id, $weight, '$lang',
                                '$text', '$ext'
                            );
                        ";
                    }
                    $weight++;
                }
                $db->query($query);

                rLocate("catalogue/product/$id");
                return;
            }

           //posun obrazkov
            if (($this->checkAccess("editor")) && (in_array($r["arg"][3], array("up-image", "down-image")))) {

         		$this->moveImage();
         		return;
            }

			$this->product($id);
			return;


        //produkty danej kategorie
        } elseif ($id = $r["arg"][1] + 0) {

         	$this->showCategory($id);
            return;
        }

		//vypis kategorii
		$this->tpl->assign("path", $this->path);
        $this->tpl->assign("categories",new Categories());
        $this->tpl->display("catalogue-cats.tpl");

        return;
    }

	/**
	 * Zobrazenie vypisu kategorie
	 *
	 * @param int $id id kategorie
	 */
    private function showCategory($id) {
    	global $db,$r;

    		$dir    = $r["root"]    . "/data/catalogue/images";
    		 $webDir = $r["webRoot"] . "/data/catalogue/images";

    	   $category = $db->getRow("
                SELECT * FROM c_categories
                WHERE id = $id AND lang = '{$r["lang"]}'
            ");

            $where = "category_id = $id AND c_products.lang = '{$r["lang"]}'";
            $pager = $this->pager(2, "catalogue/$id", "products", "c_products", $where);

            $products = $db->getArrRow("
                SELECT c_products.*, c_product_images.extension FROM c_products
                LEFT JOIN c_product_images
                   ON c_product_images.id = c_products.default_image
                  AND c_product_images.lang = '{$r["lang"]}'
                WHERE $where AND c_products.lang = '{$r["lang"]}'
                ORDER BY c_products.weight
                {$pager["limit"]}
            ");

            foreach ($products as &$p) {
                if (($p["default_image"]) && (file_exists("$dir/{$p["default_image"]}-thumb.{$p["extension"]}")))
                    $p["image"] = "{$webDir}/{$p["default_image"]}-thumb.{$p["extension"]}";

               $p[details]=$db->getArrRow("
                    SELECT * FROM c_product_details
                    WHERE product_id = {$p[id]} AND lang = '{$r["lang"]}'
                    ORDER BY weight
                ");

                $p[images]=$db->getArrRow("
                    SELECT * FROM c_product_images
                    WHERE product_id = {$p[id]} AND lang = '{$r["lang"]}'
                    ORDER BY weight
                ");

            }

            $this->tpl->assign("category", $category);
            $this->tpl->assign("products", $products);

            //rPrint($products);

            $this->active_category = $category["id"] + 0;
            $this->genPath();

	    	$this->tpl->assign("path", $this->path);


            $this->tpl->display("catalogue-list.tpl");
            return;


    }

	/**
	 * Metod generuje cestu yanorenia v kategoria a vytvara breadcumbs
	 */
    private function genPath() {
        global $r;

        if ($this->active_category) {

            $tree = new RTree("c_categories", "id", "parent_id");
            $tree->setQuery("path", "
                SELECT * FROM %TABLE%
                WHERE %ID% = %d AND lang = '{$r["lang"]}'
            ");
            $path = $tree->getPath(array("id" => $this->active_category));

            foreach ($path as $p) {

                $this->path[] = array(
                    "catalogue/{$p["id"]}",
                    $r["lang"] => $p["title"]
                );

            }
        }
    }


	/**
	 * Strankovanie
	 *
	 * @param int $arg cislo strany v argumente
	 * @param array $pager strankovac
	 * @param int $pp pocet poloziek na stranu
	 * @param string $table nazov tabulky
	 * @param string $where podmienka
	 *
	 * @return object
	 */
    private function pager($arg, $pager, $pp, $table, $where = "") {
        global $db, $r;

        $page  = $r["arg"][$arg] + 0; if (!$page) $page = 1;
        if (!($pp+0)) $pp = $this->cfg["catalogue_{$pp}_pp"];
        $limit = "LIMIT $pp OFFSET " . (($page-1) * $pp);

        $count = $db->getCell("SELECT COUNT(id) FROM $table " . ($where ? "WHERE $where" : ""));
        $pages = ceil($count / $pp);

        if ($page > 1) {
            $this->tpl->assign("prev", $page-1);
            $this->tpl->assign("first", 1);

        } if ($page < $pages) {
            $this->tpl->assign("next", $page+1);
            $this->tpl->assign("last", $pages);
        }
        $this->tpl->assign("pager", $pager);
        $this->tpl->assign("page",  $page);
        $this->tpl->assign("pages", $pages);
        $this->tpl->assign("count", $count);

        return array(
            "limit"     => $limit,
            "from"      => ($page-1) * $pp,
            "page"      => $page,
            "pages"     => $pages,
            "pp"        => $pp,
            "count"     => $count,
        );
    }

	/**
	 * Zmazanie obrazka
	 *
	 * @param int $id id obrazka
	 * @param bool $delete_from_db zmazat z DB
	 */
    public static function deleteImage($id, $delete_from_db = true) {
        global $db, $r;

        $dir = $r["root"] . "/data/catalogue/images";

        $files = rDirList($dir, array("^$id\.", "^$id-thumb\."));
        foreach ($files as $f) {
            unlink("$dir/$f");
        }

        if ($delete_from_db) {
            $db->query("
                DELETE FROM c_product_images
                WHERE id = $id
            ");
        }
    }

	/**
	 * Zmazanie vsetkych obrazkov produktu
	 *
	 * @param int $id id produktu
	 * @param bool $delete_from_db zmazat z DB
	 */
    public static function deleteAllImages($id, $delete_from_db = true) {
        global $db, $r;

        $images = $db->getCol("
            SELECT id FROM c_product_images
            WHERE product_id = $id
        ");
        foreach ($images as $image) {
            self::deleteImage($image, false);
        }
        if ($delete_from_db) {
            $db->query("
                DELETE FROM c_product_images
                WHERE product_id = $id
            ");
        }
    }

	/**
	 * Metoda na zobrazenie obsahu nakupneho kosika
	 *
	 * @param boolean new - ak true, kosik sa zobrazuje po pridani polozky, inak bez pridania
	 */
    private function showCart($new=true) {
    	global $db,$r;

			 $this->path[] = array(
				"cart",
				i18n::t("cat_cart")
			);

    		$data=array();
    		$i=0;

    		$spolu = 0;

			//nazvy poloziek podla kosika v sessions
    		foreach ($_SESSION[cart] as $key=>$item ) {
				$obj = $db->getRow("SELECT * FROM c_products WHERE id={$item[id]} AND c_products.lang = '{$r["lang"]}'");

    			$data[$i][pocet]=$item[pocet];
    			$data[$i][id]=$key;
    			$data[$i][nazov]=$obj[title];
    			$data[$i][cena]=$data[$i][pocet] * $obj[price]." ".$obj[currency];
    			$spolu += $data[$i][pocet] * $obj[price];
    			$i++;
    		}

    		$_SESSION[ref]=$_SERVER[HTTP_REFERER];
			$this->tpl->assign("spolu", $spolu);
			$this->tpl->assign("currency", $obj[currency]);
			$this->tpl->assign("path", $this->path);
    		$this->tpl->assign("ref",$_SESSION[ref]);
    		$this->tpl->assign("new",$new);
    		$this->tpl->assign("data",$data);
    		$this->tpl->display("cart.tpl");

    }

	/**
	 * posuvanie obrazkov
	 */
    private function moveImage() {
    	global $db,$r;

    	       list($direction, $type) = explode("-", $r["arg"][3]);

                $image_id    = $r["arg"][4] + 0;
                $id = $r["arg"][2] + 0;

                $object1 = $db->getRow("
                    SELECT id, weight FROM c_product_images WHERE id = $image_id
                ");

                $object2 = $db->getRow("
                    SELECT id, weight FROM c_product_images
                    WHERE weight " . ($direction == "up" ? "<" : ">") . " {$object1["weight"]}
                      AND product_id = $id AND lang = '{$r["lang"]}'
                    ORDER BY weight " . ($direction == "up" ? "DESC" : "") . "
                ");

                if ($object2) {
                    $db->query("
                        UPDATE c_product_images SET weight = {$object2["weight"]}
                        WHERE id = {$object1["id"]};

                        UPDATE c_product_images SET weight = {$object1["weight"]}
                        WHERE id = {$object2["id"]};
                    ");
                }
//die();
                rLocate("catalogue/product/$id");
                return;
    }


    /**
     * Spracovanie objednavky
     */
    private function processOrder() {
    	global $db,$r;

    	$email = $this->cfg["catalogue_email"];

		$text = "".i18n::t("cart_contacts")."\n\n".i18n::t("name_firm").": {$_POST[meno]}\n".i18n::t("contact_person")."\n".i18n::t("street").": {$_POST[ulica]}\n".i18n::t("zip").": {$_POST[psc]}\n".i18n::t("city").": {$_POST[mesto]}\n".i18n::t("phone").": {$_POST[telefon]}\n".i18n::t("fax").": {$_POST[fax]}\n".i18n::t("email").": {$_POST[email]}\n\n".i18n::t("cart_products").":\n\n";

		if (count($_SESSION[cart])>0)
			foreach ($_SESSION[cart] as $obj) {
				$data = $db->getRow("SELECT title FROM c_products WHERE id={$obj[id]} AND c_products.lang = '{$r["lang"]}'");

				$text.="\n".$obj[pocet]." - ".$data[title]." - ".$data[price]*$obj[pocet]." - ".$data[currency];
			}

		$text=iconv("UTF-8","CP1250",$text);

		mail($email,"Objednavka",$text);
		unset($_SESSION[cart]);
		//return;


		$this->status(
				i18n::t("cat_msg1"),
				i18n::t("cat_msg2")
				);



    }

	/**
	 * Metoda na pridanie polozky katalogu do kosika
	 */
    private function AddToCart() {

	    	$obj[id]=$_POST[id];
			$obj[pocet]=$_POST[pocet];

			$inc=false;;

			//ak uz je polozka v kosiku, zvysit pocet
			foreach ($_SESSION[cart] as &$item) {

					if ($item[id]==$obj[id]) {
						$item[pocet]+=$obj[pocet];
						$inc=true;
					}
			}

			if (!$inc) {
				$id="{$obj[id]}-{$obj[pocet]}";

				$_SESSION[cart][$id]=$obj; //kosik v sessions
			}

			$this->showCart(); //zobrazenie kosika
			return;
    }


	/**
	 * Metoda odoberie polozku z kosika
	 *
	 * @param int $id id polozky
	 */
    private function removeFromCart($id) {
    	global $db,$r;

 			unset($_SESSION[cart][$id]);

				$data=array();
    		$i=0;

    		foreach ($_SESSION[cart] as $item) {

    			$data[$i][pocet]=$item[pocet];
    			$data[$i][nazov]=$db->getCell("SELECT title FROM c_products WHERE id={$item[id]} AND c_products.lang = '{$r["lang"]}'");
    			$i++;
    		}

    		$this->tpl->assign("ref",$_SESSION[ref]);
    		$this->tpl->assign("data",$data);
    		$this->tpl->display("cart.tpl");

    }

	/**
	 * Zobrazenie detailu produktu
	 *
	 * @param int $id id produktu
	 */
    private function product($id) {
    	global $db,$r;

			//cesty
	        $dir    = $r["root"]    . "/data/catalogue/images";
	        $webDir = $r["webRoot"] . "/data/catalogue/images";

            $product = $db->getRow("
                SELECT c_products.*, c_product_images.extension FROM c_products
                LEFT JOIN c_product_images
                   ON c_product_images.id = c_products.default_image
                  AND c_product_images.lang = '{$r["lang"]}'
                WHERE c_products.id = $id AND c_products.lang = '{$r["lang"]}'
            ");

            $category = $db->getRow("
                SELECT * FROM c_categories
                WHERE id = {$product["category_id"]} AND lang = '{$r["lang"]}'
            ");

            $this->active_category = $category["id"] + 0;
            $this->genPath();
            $this->path[] = array(
                "catalogue/product/$id",
                $r["lang"] => $product["title"]
            );

            $this->tpl->assign("category", $category);

                $product["details"] = $db->getArrRow("
                    SELECT * FROM c_product_details
                    WHERE product_id = $id AND lang = '{$r["lang"]}'
                    ORDER BY weight
                ");

                // predvoleny obrazok
                if (($product["default_image"]) && (file_exists("$dir/{$product["default_image"]}.{$product["extension"]}")))
                    $product["image"] = "{$webDir}/{$product["default_image"]}-thumb.{$product["extension"]}";

                // obrazky
                $images = $db->getArrRow("
                    SELECT * FROM c_product_images
                    WHERE product_id = $id AND lang = '{$r["lang"]}'
                    ORDER BY weight
                ");
                foreach ($images as &$image) {
                    $image["image"] = "{$webDir}/{$image["id"]}-thumb.{$image["extension"]}";
                    $image["image_full"] = "{$webDir}/{$image["id"]}.{$image["extension"]}";
                }
                if ((count($images) == 1) && ($images[0]["id"] == $product["default_image"])) unset($images);
                $this->tpl->assign("images",   $images);

                $this->tpl->assign("product",  $product);
                $this->tpl->assign("path",  $this->path);

                $this->tpl->assign("input", $this->cfg["catalogue_images_upload_count"] + 1);

                $this->tpl->display("catalogue-product.tpl");
                return;
            /*}*/

    }




}

/**
 * Trieda reprezentujuca kategorie - aby mohol byt v sablone vygenerovany strom
 * bez obmedzenia hlbky
 */
class Categories {
	private $nodes;
	private $tree;

	public function __construct() {
		global $r,$db;

		 //pre vsetky menu - hlavne a bocne
			$tree = new rTree("c_categories", "id", "parent_id");
			$tree->setQuery("tree", "
                SELECT t1.%ID%, t1.title, COUNT(t2.%ID%) AS count
                FROM %TABLE% t1
                LEFT JOIN %TABLE% t2
                   ON t2.%PARENT_ID% = t1.%ID%
                  AND t2.lang = '{$r["lang"]}'
                WHERE t1.%PARENT_ID% = %d
                  AND t1.lang = '{$r["lang"]}'
                GROUP BY t1.%ID%, t1.weight, t1.title
                ORDER BY t1.weight, t1.%ID%
            "); // vygerovanie menu stromu

			$this->nodes = $tree->getMultiTree(0, $this->active_menu + 0,true); // ziskanie menu zo stromu

			$this->generateTree($this->nodes);

	}

	/**
	 * Vygenerovanie stromu kategorii
	 *
	 * @param array $nodes polozky stromu
	 */
	private function generateTree($nodes) {

		$this->tree .= "<ul>\n";

		foreach ((array)$nodes as $node) { // pre kazdu polozku

			$this->tree .= "<li><a href=\"" . rUrl("catalogue/{$node["id"]}") . "\">{$node["title"]}</a>";

			if (count($node["children"])) //ak ma polozka podpolozku
			$this->generateTree($node["children"]); // vygeneruj podmenu

			$this->tree .= "</li>\n";
		}

		$this->tree .= "</ul>\n";

	}

	/**
	 * Vykreslenie stromu
	 */
	public function render() {

			echo $this->tree;

	}
}

?>
